package com.yami.shop.delivery.platform.controller;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.PhoneUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.enums.DvyType;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.bean.model.UserAddrOrder;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PrincipalUtil;
import com.yami.shop.delivery.common.model.DeliveryOrder;
import com.yami.shop.delivery.common.model.OrderSelfStation;
import com.yami.shop.delivery.common.param.DeliveryOrderItemParam;
import com.yami.shop.delivery.common.param.DvyOrderParam;
import com.yami.shop.delivery.common.param.OrderParam;
import com.yami.shop.delivery.common.service.DeliveryOrderService;
import com.yami.shop.delivery.common.service.OrderSelfStationService;
import com.yami.shop.service.DeliveryService;
import com.yami.shop.service.OrderItemService;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.UserAddrOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import com.yami.shop.common.util.BeanUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author lhd on 2020/05/15.
 */
@Slf4j
@RestController
@RequestMapping("/platform/orderDelivery")
@Tag(name = "平台端订单物流接口")
public class OrderDeliveryController {

    @Value("${yami.expose.operation.auth:}")
    private Boolean permission;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserAddrOrderService userAddrOrderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private DeliveryOrderService deliveryOrderService;

    @Autowired
    private DeliveryService deliveryService;



    @Autowired
    private OrderSelfStationService orderSelfStationService;

    @PutMapping("/getOrderDeliveries/{orderNumber}")
    @Operation(summary =  "查询订单物流包裹信息")
    @Parameter(name = "orderNumber", description = "订单号", required = true)
    public ServerResponseEntity<List<DeliveryOrder>> getOrderDeliveries(@PathVariable("orderNumber") String orderNumber) {
        List<DeliveryOrder> deliveryOrders = deliveryOrderService.listDetailDelivery(orderNumber);
        return ServerResponseEntity.success(deliveryOrders);
    }

    @PutMapping("/updateOrderDeliveries")
    @Operation(summary =  "修改订单物流包裹信息")
    public ServerResponseEntity<Void> updateOrderDeliveries(@RequestBody DvyOrderParam dvyOrderParam) {
        List<DeliveryOrder> deliveryOrders = dvyOrderParam.getDeliveryOrders();
        deliveryOrderService.updateOrderDeliveries(deliveryOrders);
        return ServerResponseEntity.success();
    }

    @PutMapping("/orderItemsDelivery")
    @Operation(summary =  "订单项分包裹发货")
    public ServerResponseEntity<Void> orderItemsDelivery(@RequestBody DeliveryOrderItemParam deliveryOrderParam) {
        Long shopId = Constant.PLATFORM_SHOP_ID;
        deliveryOrderService.saveDeliveriesInfo(deliveryOrderParam, shopId);
        return ServerResponseEntity.success();
    }

    @GetMapping("/getOrderItemUnDelivery/{orderNumber}")
    @Operation(summary =  "订单项待发货数量查询")
    @Parameter(name = "orderNumber", description = "订单号", required = true)
    public ServerResponseEntity<Order> getOrderItemUnDelivery(@PathVariable("orderNumber") String orderNumber) {
        Long shopId = Constant.PLATFORM_SHOP_ID;
        Order order = orderService.getOrderByOrderNumberAndShopId(orderNumber,shopId,true);
        UserAddrOrder userAddrOrder = userAddrOrderService.getById(order.getAddrOrderId());
        order.setUserAddrOrder(userAddrOrder);
        List<OrderItem> orderItems = orderItemService.list(new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getOrderNumber, orderNumber).eq(OrderItem::getShopId, shopId));
        if(CollectionUtils.isEmpty(orderItems)){
            // 订单不存在
            throw new YamiShopBindException("yami.order.no.exist");
        }
        Map<Long,Integer> orderItemMap = null;
        if (Objects.nonNull(order.getRefundStatus())){
            orderItemMap = orderService.getOrderItemMap(order.getOrderId());
        }
        //查询已发货数量
        for (OrderItem orderItem : orderItems) {
            //根据状态查询可发货数量
            orderItem.setChangeNum(orderItem.getStatus() == -1 ?orderItem.getProdCount():orderItem.getStatus());
            orderItem.setProdCount(orderItem.getChangeNum());
            if (Objects.nonNull(orderItemMap) && Objects.nonNull(orderItemMap.get(orderItem.getOrderItemId()))){
                orderItem.setReturnMoneySts(orderItemMap.get(orderItem.getOrderItemId()));
            }else if (Objects.nonNull(orderItemMap) && Objects.nonNull(orderItemMap.get(0L))){
                orderItem.setReturnMoneySts(orderItemMap.get(0L));
            }
        }
        order.setOrderItems(orderItems);
        return ServerResponseEntity.success(order);
    }

    @GetMapping("/orderInfo/{orderNumber}")
    @Operation(summary =  "根据订单号获取订单物流信息")
    @Parameter(name = "orderNumber", description = "订单号", required = true)
    public ServerResponseEntity<OrderParam> info(@PathVariable("orderNumber") String orderNumber) {
        Order order = orderService.getOrderDetailByOrderNumberAndShopId(orderNumber,null);
        // 处理下赠品
        List<OrderItem> orderItemDbList = orderItemService.getOrderItemsByOrderNumber(orderNumber);
        Map<Long, List<OrderItem>> giveawayMap = orderItemDbList.stream().filter(item -> Objects.nonNull(item.getGiveawayOrderItemId()))
                .collect(Collectors.groupingBy(OrderItem::getGiveawayOrderItemId));
        for (OrderItem orderItem : order.getOrderItems()) {
            // 放入赠品
            if(giveawayMap.containsKey(orderItem.getOrderItemId())){
                orderItem.setGiveawayList(giveawayMap.get(orderItem.getOrderItemId()));
            }
        }

        if (Objects.nonNull(order.getDvyType()) && order.getDvyType().equals(DvyType.STATION.value())){
            OrderSelfStation orderSelfStation = orderSelfStationService.getOne(new LambdaQueryWrapper<OrderSelfStation>().eq(OrderSelfStation::getOrderNumber, order.getOrderNumber()));
            if (Objects.nonNull(orderSelfStation.getStationUserMobile()) && BooleanUtil.isFalse(permission)){
                order.getUserAddrOrder().setMobile(PhoneUtil.hideBetween(orderSelfStation.getStationUserMobile()).toString());
            } else {
                order.getUserAddrOrder().setMobile(orderSelfStation.getStationUserMobile());
            }
            order.getUserAddrOrder().setReceiver(orderSelfStation.getStationUserName());
        } else if (BooleanUtil.isFalse(permission)) {
            order.setUserMobile(PhoneUtil.hideBetween(order.getUserMobile()).toString());
            if (PrincipalUtil.isMobile(order.getNickName())) {
                order.setNickName(PhoneUtil.hideBetween(order.getNickName()).toString());
            }
            if(Objects.nonNull(order.getUserAddrOrder()) && Objects.nonNull(order.getUserAddrOrder().getMobile())) {
                order.getUserAddrOrder().setMobile(PhoneUtil.hideBetween(order.getUserAddrOrder().getMobile()).toString());
            }
        }

        OrderParam orderParam = BeanUtil.map(order, OrderParam.class);
        orderParam.setFreeFreightAmount(order.getFreeTransfee());
        orderParam.setScore(orderParam.getOrderItems().stream().mapToLong(OrderItem::getUseScore).sum());
        //查询包裹信息
        List<DeliveryOrder> deliveryOrders = deliveryOrderService.getAndDeliveryItemInfo(orderNumber);
        orderParam.setDeliveryExpresses(deliveryOrders);
        return ServerResponseEntity.success(orderParam);
    }

    @GetMapping("/deliveryOrder/{orderDeliveryId}")
    @Operation(summary =  "物流包裹查询接口", description = "根据orderDeliveryId查询订单包裹信息")
    @Parameter(name = "orderDeliveryId", description = "订单物流包裹id")
    public ServerResponseEntity<DeliveryOrder> info(@PathVariable("orderDeliveryId") Long orderDeliveryId) {
        DeliveryOrder deliveryOrder = deliveryOrderService.deliveryOrderItemInfo(orderDeliveryId);
        return ServerResponseEntity.success(deliveryOrder);
    }
}
